package atom.core0.concurrent;
/**
 * Title: 信号量的管理
 * Description:
 * Copyright: Copyright (c) 2010
 * @author hike_man@126.com
 * @version 1.0
 */
import java.util.concurrent.TimeoutException;

import org.apache.log4j.Logger;

public class MySemaphore
{
	private static final Logger logger = Logger.getLogger(MySemaphore.class);
	private int count;
	private int maxCount;

	public MySemaphore(int count)
	{
		this.count = 0;
		this.maxCount = count;
	}

	synchronized public void acquire()
	{// throws InterruptedException{
		while (count >= maxCount)
		{
			try
			{
				wait();
			} catch (InterruptedException e)
			{
				
				logger.debug(e,e);
			}
		}
		count++;
	}

	//超时 秒
	synchronized public void acquire(long timeout) throws TimeoutException
	{
		while (count >= maxCount)
		{
			try
			{
				long start = System.currentTimeMillis();
				wait(timeout*1000);
				long now  = System.currentTimeMillis();
				
				//notify唤醒 或者超时 
				//超时不会有异常
				if (now - start>=timeout*1000)
				{
					throw new TimeoutException("获取信号量超时");
				}
			}
			//特殊的中断异常
			catch (InterruptedException e)
			{
				logger.debug(e,e);
				throw new TimeoutException("获取信号量时被中断");
			}
		}
		count++;
	}
	synchronized public void release()
	{
		count--;
		notify();
	}

	synchronized public boolean setCount(int count)
	{
		if (count>= this.count)
		{
			this.maxCount = count;
			return true;
		}
		return false;
		
	}

	public boolean canUsed()
	{
		if (count < maxCount)
			return true;
		else
			return false;
	}

	/**
	 * @return Returns the maxCount.
	 */
	public synchronized int getMaxCount() {
		return maxCount;
	}

	/**
	 * @return Returns the count.
	 */
	public synchronized int getCount() {
		return count;
	}
}

//没有使用Semaphore的原因是，Semaphore无法动态调整信号量大小
//CountDownLatch 是等大家都跑完了再继续；CyclicBarrier 是等大家准备好了一起跑；Semaphore 是只允许一定数量的跑
